package com.myapp.ruyixing.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.Message;
import com.myapp.ruyixing.model.ShopPhotoClass;
import com.myapp.ruyixing.model.ShopPhotoClass.ShopPhotoClassItem;
import com.myapp.ruyixing.ui.widget.PhotoPickFragment.PhotoPickCompleteListener;
import com.myapp.ruyixing.ui.widget.PhotoTypePickFragment;
import com.myapp.ruyixing.ui.widget.TitleBar;
import com.myapp.ruyixing.utils.ImageUtils;

public class UploadPhotoActivity extends BaseActivity implements
		OnClickListener, PhotoPickCompleteListener {

	private LinearLayout mPhotoLayout;
	private View mEmptyPhotoView;

	private List<PhotoAbs> mPhotos;

	private Button mNameView;
	private View mInfoBox;
	private Spinner mClassView;

	private View mSelectedPhotoView;
	private View mLoadingView;

	private String mShopId;
	private ShopPhotoClass mTopClassForPhoto;
	private List<String> mTopClassIds;

	private int mCurrSelectedItem = -1;

	private static class PhotoAbs {
		public String typeid;
		public String name;
		public String file;

		public int topClassPosition;
	}

	private RYHttpResponseHandler mUploadHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			mLoadingView.setVisibility(View.GONE);

			Message message = (Message) o;
			if (message != null) {
				Toast.makeText(UploadPhotoActivity.this, "上传成功",
						Toast.LENGTH_SHORT).show();
			}

			if (message.errno == 0) {
				finish();
			}
		}

		@Override
		public void onFailure(Throwable throwable) {
			mLoadingView.setVisibility(View.GONE);
			Toast.makeText(UploadPhotoActivity.this, "上传图片失败",
					Toast.LENGTH_SHORT).show();
		}
	};

	private RYHttpResponseHandler mHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			mTopClassForPhoto = (ShopPhotoClass) o;

			if (mTopClassForPhoto != null && mTopClassForPhoto.data != null) {
				List<String> names = new ArrayList<String>();
				mTopClassIds = new ArrayList<String>();
				for (ShopPhotoClassItem item : mTopClassForPhoto.data) {
					names.add(item.name);
					mTopClassIds.add(item.id);
				}
				ArrayAdapter<String> sAdapter = new ArrayAdapter<String>(
						UploadPhotoActivity.this,
						android.R.layout.simple_spinner_dropdown_item, names);
				sAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				mClassView.setAdapter(sAdapter);
			}
		}

		@Override
		public void onFailure(Throwable throwable) {
			if (!isFinishing()) {
				Toast.makeText(getApplicationContext(), "加载失败",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		setContentView(R.layout.activity_upload_photo);

		initView();

		mShopId = getIntent().getStringExtra(ShopDetailActivity.INTENT_SHOP_ID);
		if (TextUtils.isEmpty(mShopId) == true) {
			Toast.makeText(getApplicationContext(), "商户为空", Toast.LENGTH_SHORT)
					.show();
		} else {
			RYHttpClient.getPhotoClass(this, mHandler, mShopId, null);
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.photo_delete:
			PhotoAbs abs = (PhotoAbs) v.getTag();
			if (abs != null) {
				int p = mPhotos.indexOf(abs);
				mPhotos.remove(p);
				mCurrSelectedItem = mPhotos.size() - 1;
				removePhotoView(p);
			}
			break;

		case R.id.upload:
			new PhotoTypePickFragment().show(getSupportFragmentManager()
					.beginTransaction(), "photo");
			break;

		case R.id.name:
			String name = (String) mClassView.getSelectedItem();
			if (TextUtils.isEmpty(name) == false) {
				String id = getClassId(name);

				if (TextUtils.isEmpty(id) == false) {
					startActivityForResult(
							new Intent(this, SelectPhotoClassActivity.class)
									.putExtra(
											ShopDetailActivity.INTENT_SHOP_ID,
											mShopId).putExtra("typeid", id),
							100);
				}
			}

			break;
		case R.id.photo_layout:
			PhotoAbs abs2 = (PhotoAbs) v.getTag();
			if (abs2 != null) {
				mCurrSelectedItem = mPhotos.indexOf(abs2);
				selectItem();
			}

			break;
		default:
			break;
		}
	}

	private void selectItem() {
		if (mCurrSelectedItem < 0) {
			mSelectedPhotoView = null;
			return;
		}
		
		View view = mPhotoLayout.getChildAt(mCurrSelectedItem);
		View nSelectedPhotoView = view.findViewById(R.id.photo);
		if (mSelectedPhotoView != nSelectedPhotoView) {
			if (mSelectedPhotoView != null) {
				mSelectedPhotoView.setSelected(false);
			}
			mSelectedPhotoView = nSelectedPhotoView;

			if (!mSelectedPhotoView.isSelected()) {
				mSelectedPhotoView.setSelected(true);
			}
		}

		PhotoAbs item = (PhotoAbs) mPhotos.get(mCurrSelectedItem);
		mClassView.setSelection(item.topClassPosition);

		if (TextUtils.isEmpty(item.name) == false) {
			mNameView.setText(item.name);
		} else {
			if (item.topClassPosition == 0) {
				mNameView.setText("选菜名...");
			} else {
				mNameView.setText("图片标题...");
			}
		}
	}

	@Override
	public void onPhotoPicker(String file) {
		if (TextUtils.isEmpty(file) == false) {
			PhotoAbs item = new PhotoAbs();
			item.file = file;

			mPhotos.add(item);

			mCurrSelectedItem = mPhotos.size() - 1;
			addPhotoView(mCurrSelectedItem);
		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);

		if (arg0 == 100 && arg1 == RESULT_OK && arg2 != null) {
			String typeid = arg2.getStringExtra("id");
			String name = arg2.getStringExtra("name");

			if (mCurrSelectedItem >= 0) {
				PhotoAbs item = mPhotos.get(mCurrSelectedItem);
				item.typeid = typeid;
				item.name = name;

				mNameView.setText(item.name);
			}

		}
	}

	private String getClassId(String name) {
		if (mTopClassForPhoto != null && mTopClassForPhoto.data != null) {
			for (ShopPhotoClassItem item : mTopClassForPhoto.data) {
				if (name.equals(item.name)) {
					return item.id;
				}
			}
		}

		return null;
	}

	private void upload() {
		if (mPhotos.size() == 1) {
			mLoadingView.setVisibility(View.VISIBLE);

			PhotoAbs abs = mPhotos.get(0);
			RYHttpClient.uploadPhotos(UploadPhotoActivity.this, mUploadHandler,
					mShopId, mPhotos.get(0).file,
					mTopClassIds.get(abs.topClassPosition), abs.typeid,
					abs.name);
		} else if (mPhotos.size() == 2) {
			mLoadingView.setVisibility(View.VISIBLE);

			PhotoAbs abs1 = mPhotos.get(0);
			PhotoAbs abs2 = mPhotos.get(1);
			RYHttpClient.uploadPhotos(UploadPhotoActivity.this, mUploadHandler,
					mShopId, mPhotos.get(0).file,
					mTopClassIds.get(abs1.topClassPosition), abs1.typeid,
					abs1.name, mPhotos.get(1).file,
					mTopClassIds.get(abs2.topClassPosition), abs2.typeid,
					abs2.name);
		}
	}

	private void initView() {
		mPhotoLayout = (LinearLayout) findViewById(R.id.photoes);

		((TitleBar) findViewById(R.id.title_bar))
				.setOnIconClickedListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onBackPressed();
					}
				});

		((TitleBar) findViewById(R.id.title_bar))
				.setOnRightIconClickedListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						upload();

					}
				});

		mPhotos = new ArrayList<UploadPhotoActivity.PhotoAbs>();
		renderDefaultPhotoLayout();

		mLoadingView = findViewById(R.id.my_loading);

		mNameView = (Button) findViewById(R.id.name);
		mNameView.setOnClickListener(this);
		mInfoBox = findViewById(R.id.info_box);

		mClassView = (Spinner) findViewById(R.id.choose_photo_type);
		mClassView.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				if (mCurrSelectedItem >= 0) {
					PhotoAbs item = mPhotos.get(mCurrSelectedItem);
					if (item.topClassPosition != position) {
						item.topClassPosition = position;
						item.name = null;
						item.typeid = null;

						if (position == 0) {
							mNameView.setText("选菜名...");
						} else {
							mNameView.setText("图片标题...");
						}
					}
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
	}

	private void renderDefaultPhotoLayout() {
		mEmptyPhotoView = LayoutInflater.from(this).inflate(
				R.layout.cell_upload_photo_empty, mPhotoLayout, false);

		mEmptyPhotoView.setOnClickListener(UploadPhotoActivity.this);
		mPhotoLayout.addView(mEmptyPhotoView);
	}

	private void updatePhotoViews() {
		if (mPhotos.size() < 2) {
			mEmptyPhotoView.setVisibility(View.VISIBLE);
		} else {
			mEmptyPhotoView.setVisibility(View.GONE);
		}
	}

	private void addPhotoView(int position) {
		View convertView = LayoutInflater.from(this).inflate(
				R.layout.cell_upload_photo, mPhotoLayout, false);

		ImageView photoView = (ImageView) convertView.findViewById(R.id.photo);
		ImageView photoDeleteView = (ImageView) convertView
				.findViewById(R.id.photo_delete);
		photoDeleteView.setOnClickListener(UploadPhotoActivity.this);
		convertView.setOnClickListener(this);

		ImageUtils.displayImage(mPhotos.get(position).file, photoView);
		photoDeleteView.setTag(mPhotos.get(position));
		convertView.setTag(mPhotos.get(position));

		mPhotoLayout.addView(convertView, position);
		selectItem();

		updatePhotoViews();
	}

	private void removePhotoView(int position) {
		mPhotoLayout.removeViewAt(position);
		selectItem();

		updatePhotoViews();
	}
}
